package com.test.nio.demo01;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class ByteBufferDemo {

	public static void main(String[] args) throws Exception {
		new ByteBufferDemo().readFile("file/1.txt");
	}

	public void readFile(String fileName) throws Exception {
		RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw");
		FileChannel fileChannel = randomAccessFile.getChannel();
		ByteBuffer byteBuffer = ByteBuffer.allocate(48);
		int size = fileChannel.read(byteBuffer);
		while(size>0){
			byteBuffer.flip(); //byteBuffer 读模式变成写模式
//			while(byteBuffer.remaining()>0){
//				System.out.print(byteBuffer.getChar());
//			}
			Charset charset = Charset.forName("UTF-8");
			System.out.print(charset.decode(byteBuffer).toString());
			
			byteBuffer.clear();
			fileChannel.read(byteBuffer);
		}
		fileChannel.close();
		randomAccessFile.close();
	}
}
